package com.example.zhu95.mytimber.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.example.zhu95.mytimber.R;
import com.example.zhu95.mytimber.adapters.ItemVdragAdapter;
import com.example.zhu95.mytimber.entity.PlayListBean;
import com.example.zhu95.mytimber.entity.SongBean;
import com.example.zhu95.mytimber.entity.SongData;
import com.example.zhu95.mytimber.listener.PopupMenuItemClickListener;
import com.example.zhu95.mytimber.ui.SongItemTouchCallBack;
import com.example.zhu95.mytimber.utils.PlaylistUtils;
import com.example.zhu95.mytimber.utils.Util;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.example.zhu95.mytimber.ConstantValue.PLAYLIST_NAME;

/**
 * @author zhu95
 */
public class PlaylistDetailActivity extends BaseActivity {

    @BindView(R.id.img_playlist_back)
    ImageView imgPlaylistBack;
    @BindView(R.id.recycler_view_playlist_detail)
    RecyclerView recyclerViewPlaylistDetail;
    @BindView(R.id.view_playlist_back)
    View viewPlaylistBack;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_playlist_name)
    TextView tvPlaylistName;
    PlayListBean playlist;

    ItemVdragAdapter itemVdragAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playlist_detail);
        ButterKnife.bind(this);

        initView();
    }

    private void initView() {
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle("");
        }

        // defect: 2018/3/8 未实现Recyclerview的进入效果
/*        Explode explode = new Explode();
        explode.setDuration(1000);
        getWindow().setEnterTransition(explode);*/

        Intent intent = getIntent();
        int foreColor = intent.getIntExtra(getString(R.string.share_playlist_fore), -1);
        if (foreColor != -1) {
            viewPlaylistBack.setBackgroundColor(foreColor);
        } else {
            viewPlaylistBack.setBackgroundColor(Util.INSTANCE.getRandomForeColor());
        }
        final String playlistName;
        try {
            playlistName = intent.getStringExtra(PLAYLIST_NAME);
            playlist = PlaylistUtils.INSTANCE.findPlaylistByTitle(playlistName);
            if (playlist == null) {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        tvPlaylistName.setText(playlistName);
        String albumArt = playlist.getAlbumArt();
        if (!TextUtils.isEmpty(albumArt)) {
            Glide.with(this).load(albumArt).centerCrop().into(imgPlaylistBack);
        } else {
            Glide.with(this).load(R.drawable.ic_empty_music2).centerCrop().into(imgPlaylistBack);
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerViewPlaylistDetail.setLayoutManager(linearLayoutManager);
        final List<String> songIDs = playlist.getSongIDs();
        List<SongBean> songs = null;
        if (songIDs != null) {
            songs = new ArrayList<>();
            for (String songID : songIDs) {
                SongBean song = SongData.findSongByID(Integer.parseInt(songID));
                if (song != null) {
                    songs.add(song);
                }
            }
        }
        itemVdragAdapter = new ItemVdragAdapter(songs, this) {
            @Override
            protected void setPopupMenu(ViewHolder holder, final int songid) {
                holder.getSongMoreVert().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PopupMenu popupMenu = new PopupMenu(v.getContext(), v);
                        Menu menu = popupMenu.getMenu();
                        if (!playlist.isDefaultList()) {
                            menu.add(R.string.remove_from_playlist)
                                    .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                                        @Override
                                        public boolean onMenuItemClick(MenuItem item) {
                                            String songIds = playlist.getSongIds();
                                            String s = Util.INSTANCE.removeSongidFromSongids(songid, songIds);
                                            playlist.setSongIds(s);
                                            playlist.save();
                                            return false;
                                        }
                                    });
                        }
                        popupMenu.getMenuInflater().inflate(R.menu.song_more_popup, menu);
                        popupMenu.setOnMenuItemClickListener(
                                new PopupMenuItemClickListener(PlaylistDetailActivity.this, songid,
                                        Util.INSTANCE.getIdsStrFormat(songs), itemVdragAdapter)
                        );
                        popupMenu.show();
                    }
                });
            }
        };
        itemVdragAdapter.setItemColor(Color.WHITE);
        recyclerViewPlaylistDetail.setAdapter(itemVdragAdapter);
        // MARK:2017/12/20 匿名内部类实现item拖拽 reference：https://www.cnblogs.com/wjtaigwh/p/6543354.html
        ItemTouchHelper songItemTouchHelper = new ItemTouchHelper(new SongItemTouchCallBack(itemVdragAdapter, songs) {
            @Override
            public void saveSequence() {
                super.saveSequence();
                //不是自动生成的列表，改变顺序后才支持保存到数据库
                if (!playlist.isDefaultList()) {
                    String idsStrFormat = Util.INSTANCE.getIdsStrFormat(songs);
                    PlayListBean newPlaylist = new PlayListBean();
                    newPlaylist.setSongIds(idsStrFormat);
                    newPlaylist.updateAll("title = ? and isdefaultlist = ? ", "" + playlist.getTitle(), "0");
                }
            }
        });
        // MARK:2017/12/20 附加到RecyclerView
        songItemTouchHelper.attachToRecyclerView(recyclerViewPlaylistDetail);
        itemVdragAdapter.setItemTouchHelper(songItemTouchHelper);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main_option_popup, menu);
        menu.findItem(R.id.action_order_by).setVisible(false);
        menu.findItem(R.id.action_search).setIcon(R.drawable.ic_search_white_24dp);

        if (playlist.isDefaultList()) {
            String clearlist = getString(R.string.clear_autolist_item, playlist.getTitle());
            menu.add(clearlist).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    if (TextUtils.equals(playlist.getTitle(), getString(R.string.recent_add))) {
                        PlaylistUtils.INSTANCE.clearRecentAddList();
                    } else if (TextUtils.equals(playlist.getTitle(), getString(R.string.recent_play))) {
                        PlaylistUtils.INSTANCE.clearRecentPlayList();
                    } else if (TextUtils.equals(playlist.getTitle(), getString(R.string.top_track))) {
                        PlaylistUtils.INSTANCE.clearMyTopSongList();
                    }
                    finish();
                    return false;
                }
            });
        } else {
            String deletelist = String.format(getString(R.string.delete_custom_list), playlist.getTitle());
            menu.add(deletelist).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    new MaterialDialog.Builder(PlaylistDetailActivity.this)
                            .title(R.string.delete_playlist)
                            .content(getString(R.string.delete_confirm, playlist.getTitle()))
                            .positiveText(R.string.delete)
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    PlaylistUtils.INSTANCE.deletePlaylist(playlist.getTitle());
                                    finish();
                                }
                            })
                            .negativeText(android.R.string.cancel)
                            .show();
                    return false;
                }
            });
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
            default:
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void updateUI(int songid, String musicState, int currentPosition) {
        super.updateUI(songid, musicState, currentPosition);
        itemVdragAdapter.notifyDataSetChanged();
    }
}
